package com.custom.BluetoothServer;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class MyService extends Service {
    private BluetoothAdapter blueAdapter;
    BluetoothServerSocket serverSocket;
    BluetoothSocket socket;
    InputStream is;
    public Callback callback = null;

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new Bind();
    }

    public class Bind extends Binder {

        public MyService getService() {
            return MyService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread() {
            @Override
            public void run() {
                try {
                    //建立连接
                    UUID uuid = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
                    blueAdapter = BluetoothAdapter.getDefaultAdapter();
                    serverSocket = blueAdapter.listenUsingRfcommWithServiceRecord("MRyan", uuid);
                    //接受客户端对象
                    socket = serverSocket.accept();
                    //接收数据流
                    is = socket.getInputStream();
                    while (true) {
                        byte[] buf = new byte[1024];
                        int count = is.read(buf);
                        String msg = new String(buf, 0, count, StandardCharsets.UTF_8);
                        Log.i("ttt", "run: 接收到的信息：" + msg);
                        if (callback != null) {
                            callback.onDataChange(msg);
                        }

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        return super.onStartCommand(intent, flags, startId);
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public Callback getCallback() {
        return callback;
    }

    public interface Callback {/*接口回调*/

        void onDataChange(String data);
    }
}
